<!--  -->
<template>
  <el-upload class="avatar-uploader" ref="uploadRef" :disabled="disabled" :headers="{ 'X-AUTH': token }"
    :action="uploadUrl" :accept="accept" :show-file-list="false" :before-upload="beforeUpload" :on-success="onSuccess"
    :on-error="onError" :on-remove="handleRemove" :on-exceed="handleExceed" :on-progress="handleProgress"
    v-loading="loading">
    <img v-if="modelValue" :src="path" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon">
      <Plus />
    </el-icon>
  </el-upload>
</template>

<script setup name="upload">
import { genFileId, ElMessage } from "element-plus";
const config =useRuntimeConfig()
const BASEURL = config.public.baseURL;
const uploadRef = ref();
const token = ''
const props = defineProps({
  modelValue: { type: String, default: "" },
  disabled: { type: Boolean, default: false },
  showFileList: { type: Boolean, default: false },
  // 数量
  limit: { type: Number, default: 1 },
  // 文件类型
  accept: { type: String, default: "" },
  fileList: {
    type: Array,
    default: () => [],
  },
  uploadUrl: { type: String, default: `` },
});

const path = ref();
const loading = ref(false);
const beforeUpload = (file) => {
  const size = 4;
  const isLt10M = file.size / 1024 / 1024 < (size || 10);
  if (!isLt10M) {
    ELMessage({ message: `上传文件不能超过 ${size}MB!`, type: "error" });
  }

  return isLt10M;
};
const handleProgress = () => {
  loading.value = true;
};
const onSuccess = (res) => {
  if (res.code === 0) {
    emit("update:modelValue", res.data.fileKey);
    path.value = BASEURL + "/upload/" + res.data.fileKey;
    ElMessage({ message: res.msg, type: "success" });
  } else {
    ElMessage({ message: res.msg, type: "error" });
  }

  uploadRef.value.clearFiles();
  loading.value = false;
};
const onError = (err, file, fileList) => {
  uploadRef.value.clearFiles();
  loading.value = false;
};
const handleRemove = (file, fileList) => {
  emit("remove");
  emit("update:modelValue", "");
};
const handleExceed = (files) => {
  uploadRef.value.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  uploadRef.value.handleStart(file);
};

watch(
  () => props.modelValue,
  () => {
    path.value = BASEURL + "/upload/" + props.modelValue;
  },
  { immediate: true }
);
const emit = defineEmits(["path", "name", "update:modelValue", "remove", "change"]);
</script>
<style lang="scss" scoped>
.avatar-uploader .avatar {
  width: 150px;
  height: 150px;
  display: block;
}

.avatar-uploader {
  ::v-deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);

    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  text-align: center;
}
</style>
